package fy.mdm.dao;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;

import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.filemanager.dao.AttachmentDAO;
import com.seeyon.ctp.common.filemanager.manager.FileManager;
import com.seeyon.ctp.common.po.filemanager.Attachment;
import com.seeyon.ctp.common.po.filemanager.V3XFile;
import com.seeyon.ctp.services.ServiceException;
import com.seeyon.v3x.services.V3XLocator;


public class FileUpload {

	private static String URL="http://10.112.17.150:80";
	private static String LOGINNAME = "084655";
/*public static void main(String[] args) throws Exception {
		String token = getToken("OAluo", "oaluo123456");
		//	String token = getToken("OAluo", "OAluo231");
			System.out.println(token);
			
			uploadFiles("D:\\xxxxxx.jpg",token);
			System.out.println(getContentType("xxxxxx.jpg"));
			

	}*/
	// 获取token
		public static String getToken(String userName, String password) throws Exception {
			URL tokeURL = new URL(URL+"/seeyon/rest/token/" + userName + "/" + password);
			System.out.println(tokeURL);
			HttpURLConnection tokenCon = (HttpURLConnection) tokeURL.openConnection();
			tokenCon.setRequestMethod("GET");
			tokenCon.setRequestProperty("contentType", "application/json");
			tokenCon.setRequestProperty("accept", "text/plain");
			InputStream input = tokenCon.getInputStream();
			InputStreamReader isr = new InputStreamReader(input, "utf-8");

			StringBuilder sb = new StringBuilder();

			char[] c = new char[1024];
			int length = 0;
			while ((length = isr.read(c)) > 0) {
				sb.append(c, 0, length);
			}
		//	System.out.println(sb);
			return sb.toString();
		}

	// 单个或多个附件上传
	// 文件绝对路径，多个文件路径中间用“|”隔开
	public static String uploadFiles(String filePath, String token) throws Exception {
		String id = "";
		if (filePath == null || "".equals(filePath)) {
			return id;
		}
		
		URL = URL + "/seeyon/uploadService.do?method=processUploadService&senderLoginName=" + LOGINNAME + "&token=" + token;
		String boundary = "---------------------------7d4a6d158c9"; // 分隔符
		URL url = new URL(URL);
		HttpURLConnection hc = (HttpURLConnection) url.openConnection();
		hc.setDoOutput(true);
		hc.setDoInput(true);
		hc.setUseCaches(false);
		hc.setRequestProperty("Content-Type", "charset=utf-8");
		hc.setRequestMethod("POST");
		hc.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
		
		byte[] end_data = ("\r\n--" + boundary + "--\r\n").getBytes();
		DataOutputStream dos = new DataOutputStream(hc.getOutputStream());
		if (filePath.indexOf("|") == -1) {
			filePath = filePath + "|";
		}
		String[] filesPathArray = filePath.split("\\|");
		
		for (int i = 0; i < filesPathArray.length; i++) {
			File file = new File(filesPathArray[i]);
			FileInputStream fis = new FileInputStream(file);
			BufferedInputStream bis = new BufferedInputStream(fis);
			String fileName = file.getName();
			// 不包含扩展名的文件名
			String fileNameWithoutExtension = fileName.substring(0, fileName.lastIndexOf("."));
			//String mimeType = getMIMEType(fileName);
			String mimeType=getContentType(fileName);
			
			StringBuffer sb = new StringBuffer();
			sb.append("--");
			sb.append(boundary);
			sb.append("\r\n");
			sb.append("Content-Disposition:form-data;\r\n name=\"" + fileNameWithoutExtension + "\"; filename=\""
					+ fileName + "\"\r\n");
			sb.append("Content-Type:" + mimeType + "\r\n\r\n");
			dos.write(sb.toString().getBytes("utf-8"));
			int cc = 0;
			while ((cc = bis.read()) != -1) {
				dos.write(cc);
			}
			if (i == filesPathArray.length - 1) {
				dos.write(end_data);
			}
			bis.close();
		}
		dos.flush();
		dos.close();
		// 开始连接
		hc.connect();
		int code = hc.getResponseCode();

		if (code != 200) {
			throw new IOException("Http请求异常:" + code);
		}
		// 读取返回数据
		StringBuilder returnData = new StringBuilder();

		try {
			InputStream is = hc.getInputStream();

			BufferedReader br = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
			char[] read = new char[512];
			int count = br.read(read, 0, 512);
			while (count > 0) {
				String str = new String(read, 0, count);
				returnData.append(str);
				System.out.println(returnData);
				count = br.read(read, 0, 512);
			}
			// 断开连接
			br.close();
			is.close();
		} catch (Exception exp) {
			exp.printStackTrace();
		} finally {
			if (hc != null) {
				hc.disconnect();
				hc = null;
			}
		}
		id = returnData.toString().trim();
		 
		return id;
	}
	
	//java 1.7以上 获取MIME类型
	public static String getContentType(String filename){
		String type = null;
		Path path = Paths.get(filename);
		try {
			type = Files.probeContentType(path);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return type;
	}



	public static String getMIMEType(String fileName) {
		String mimeType = "";
		String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
		if (ext.equals("xls") || ext.equals("xlsx") || ext.equals("xla")) {
			mimeType = "application/msexcel";
		} else if (ext.equals("doc") || ext.equals("docx") || ext.equals("dot")) {
			mimeType = "application/msword";
		} else if (ext.equals("pdf")) {
			mimeType = "application/pdf";
		} else if (ext.equals("rtf")) {
			mimeType = "application/rtf";
		} else if (ext.equals("exe")) {
			mimeType = "application/octet-stream";
		} else if (ext.equals("jpeg") || ext.equals("jpg") || ext.equals("jpe")) {
			mimeType = "image/jpeg";
		} else if (ext.equals("gif")) {
			mimeType = "image/gif";
		} else if (ext.equals("mp3")) {
			mimeType = "audio/mpeg";
		} else if (ext.equals("txt")) {
			mimeType = "text/plain";
		} else if (ext.equals("rmvb")) {
			mimeType = "video/vnd.rn-realvideo";
		} else if (ext.equals("mpeg") || ext.equals("mpg") || ext.equals("mpe")) {
			mimeType = "video/mpeg";
		} else if (ext.equals("qt") || ext.equals("mov")) {
			mimeType = "video/quicktime";
		}
		return mimeType;
	}
	
	public long[] createFileAttachmentID(long flowid, long[] reference_fileid, long[] field_id)
	  {
	    try
	    {
	    	System.out.println("~~~~~~~~~~~~~~~~8888888");
	      AttachmentDAO dao = (AttachmentDAO)V3XLocator.getInstance().lookup(AttachmentDAO.class);
	      FileManager fm = (FileManager)V3XLocator.getInstance().lookup(FileManager.class);
	      
	      long[] attachmentids = new long[reference_fileid.length];
	      for (int i = 0; i < reference_fileid.length; i++)
	      {
	        V3XFile vf = fm.getV3XFile(Long.valueOf(reference_fileid[i]));
	        Attachment attachment = new Attachment();
	        attachment.setCategory(Integer.valueOf(2));
	        attachment.setCreatedate(new Date());
	        
	        attachment.setFilename(vf.getFilename());
	        attachment.setFileUrl(vf.getId());
	        

	        attachment.setMimeType(vf.getMimeType());
	        attachment.setNewId();
	        attachment.setReference(Long.valueOf(flowid));
	        attachment.setSubReference(Long.valueOf(field_id[i]));
	        attachment.setType(Integer.valueOf(0));
	        attachment.setSize(vf.getSize());
	        attachment.setSort(0);
	        dao.save(attachment);
	        attachmentids[i] = attachment.getId().longValue();
	      }
	      return attachmentids;
	    }
	    catch (ServiceException e)
	    {
	      e.printStackTrace();
	    }
	    catch (BusinessException e)
	    {
	      e.printStackTrace();
	    }
	    return null;
	  }
	
}
